package com.kly.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kly.domain.dto.pircture.PictureCommentQueryRequest;
import com.kly.domain.entity.PictureComment;
import com.kly.domain.entity.User;
import com.kly.domain.vo.PictureCommentVO;
import com.kly.domain.vo.UserVO;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.kly.manager.auth.StpKit;
import com.kly.mapper.PictureCommentMapper;
import com.kly.service.PictureCommentService;
import com.kly.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.kly.constants.RedisConstant.PICTURE_COMMENT_LIKE_KEY;

/**
 * @author admin
 * @description 针对表【picture_comment(图片评论)】的数据库操作Service实现
 * @createDate 2025-03-24 13:36:46
 */
@Service
public class PictureCommentServiceImpl extends ServiceImpl<PictureCommentMapper, PictureComment>
        implements PictureCommentService {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addComment(Long pictureId, String comment, User loginUser) {
        // 判断参数是否存在
        if (pictureId == null || StrUtil.isBlank(comment) || loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "comment 参数为空");
        }
        ThrowUtils.throwIf(comment.length() > 100, ErrorCode.PARAMS_ERROR, "comment 长度不能超过100");
        PictureComment pictureComment = new PictureComment();
        pictureComment.setPictureId(pictureId);
        pictureComment.setUserId(loginUser.getId());
        pictureComment.setContent(comment);
        boolean save = this.save(pictureComment);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "评论失败");
    }

    @Override
    public Page<PictureCommentVO> listPictureCommentByPage(PictureCommentQueryRequest pictureCommentQueryRequest) {
        ThrowUtils.throwIf(pictureCommentQueryRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        Long pictureId = pictureCommentQueryRequest.getPictureId();
        int current = pictureCommentQueryRequest.getCurrent();
        int pageSize = pictureCommentQueryRequest.getPageSize();
        Page<PictureComment> page = this.lambdaQuery()
                .eq(PictureComment::getPictureId, pictureId)
                .orderByDesc(PictureComment::getCreateTime)
                .page(new Page<>(current, pageSize));

        //     新建Page<PictureCommentVO>
        Page<PictureCommentVO> pictureCommentVOPage = new Page<>();
        List<PictureComment> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pictureCommentVOPage;
        }
        // 多表联查
        // 获取PictureVO
        List<PictureCommentVO> pictureCommentVOList = records.stream().map(PictureCommentVO::objToVo).collect(Collectors.toList());
        // 获取userId
        Set<Long> userIdList = records.stream().map(PictureComment::getUserId).collect(Collectors.toSet());
        // 根据id分类获取user
        Map<Long, List<User>> userIdUserMap = userService.listByIds(userIdList).stream().collect(Collectors.groupingBy(User::getId));
        pictureCommentVOList.forEach(pictureCommentVO -> {
            Long userId = pictureCommentVO.getUserId();
            if (userIdUserMap.containsKey(userId)) {
                List<User> userList = userIdUserMap.get(userId);
                User user = userList.get(0);
                UserVO userVO = userService.getUserVo(user);
                pictureCommentVO.setUserVO(userVO);
            }
            this.setIsThumb(pictureCommentVO, userId);
        });
        pictureCommentVOPage.setRecords(pictureCommentVOList);
        pictureCommentVOPage.setTotal(page.getTotal());
        return pictureCommentVOPage;
    }

    @Override
    public boolean doThumb(Long commentId) {
        // 获取用户id
        Long userId = StpKit.SPACE.getLoginIdAsLong();
        // 判断是否点赞
        String key = PICTURE_COMMENT_LIKE_KEY + commentId;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        if (!Boolean.TRUE.equals(isMember)) {
            // 未点赞，点赞 更新数据库
            boolean update = this.lambdaUpdate()
                    .eq(PictureComment::getId, commentId)
                    .setSql("thumb_count = thumb_count + 1")
                    .update();
            // 添加zSet点赞
            if (update) {
                stringRedisTemplate.opsForSet().add(key, userId.toString());
            }
        } else {
            // 已点赞，取消点赞
            boolean update = this.lambdaUpdate()
                    .eq(PictureComment::getId, commentId)
                    .setSql("thumb_count = thumb_count - 1")
                    .update();
            // 移除zSet点赞
            if (update) {
                stringRedisTemplate.opsForSet().remove(key, userId.toString());
            }
        }
        return true;

    }

    @Override
    public void setIsThumb(PictureCommentVO pictureCommentVO, Long userId) {
        // 判断是否点赞
        String key = PICTURE_COMMENT_LIKE_KEY + pictureCommentVO.getId();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        pictureCommentVO.setIsThumb(Boolean.TRUE.equals(isMember));
    }


}




